package org.custom.spring.boot.security.service.impl;

import org.custom.spring.boot.security.entity.SystemUser;
import org.custom.spring.boot.security.service.SystemResourceService;
import org.custom.spring.boot.security.token.TokenManager;
import org.custom.spring.boot.security.utils.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import static org.custom.spring.boot.security.constant.SecurityConstant.PATTERN_ANY;

/**
 * 系统相关资源服务
 *
 * @author LiKun
 * @date 2021/11/11 20:23
 */
@Service("systemResourceService")
public class SystemResourceServiceImpl implements SystemResourceService {
    private static String TOKEN_PATTERN;

    @Autowired
    private TokenManager tokenManager;
    @Resource
    private transient RedisTemplate redisTemplate;

    @PostConstruct
    public void initialize() {
        TOKEN_PATTERN = tokenManager.getPrefixOfTokenKey() + PATTERN_ANY;
    }

    @Override
    public SystemUser getCurrentUser() {
        String tokenKey = SecurityUtil.getCredentials();
        return (SystemUser) redisTemplate.boundValueOps(tokenKey).get();
    }

    @Override
    public List<SystemUser> getActivityUsers() {
        Set<String> keys = redisTemplate.keys(TOKEN_PATTERN);
        List<SystemUser> result = new ArrayList<>(keys.size());
        keys.forEach(key -> result.add((SystemUser) redisTemplate.boundValueOps(key).get()));

        return result;
    }
}
